import requests
import execjs
import re
from loguru import logger
import json


session = requests.Session()
url = 'http://www.gsxt.gov.cn/index.html'

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36'
}

# 第一次请求
res = session.get(url=url,headers=headers)
# print(res)
cookie_pattern = 'cookie=(.*?);location'
cookie_js = re.findall(cookie_pattern,res.text)[0]
# print(cookie_js)
cookie_ = execjs.eval(cookie_js)
logger.info(res.cookies)
logger.info('第一页的cookie是: '+cookie_)
# print(cookie_)

# 第二次请求
session.cookies.update({cookie_.split("=")[0]: cookie_.split("=")[1]})
res2 = session.get(url=url,headers=headers).text

# logger.info('第二页返回的内容: ' + res2)
go_data = re.findall('};go\((.*?)\)</script>',res2)[0]
go_data_ = json.loads(go_data)
# print(go_data_ )
# print(type(go_data_ ))


if go_data_['ha'] == 'md5':
    f = open('jsl_md5.js',encoding='utf-8')
    js_ = execjs.compile(f.read())

elif go_data_['ha'] == 'sha1':
    f = open('jsl_sha1.js',encoding='utf-8')
    js_ = execjs.compile(f.read())

elif go_data_['ha'] == 'sha256':
    f = open('jsl_sha256.js',encoding='utf-8')
    js_ = execjs.compile(f.read())

else:
    logger.warning('错误,请检查加密类型.')

go_ = js_.call('go',go_data_)
# logger.info(go_)
session.cookies.update({go_.split("=")[0]: go_.split("=")[1]})
# logger.info(session.cookies)


#第三次请求
res3 = session.get(url=url,headers=headers).text
print(res3)